package com.library.servlet.user;

import com.library.dao.BorrowRecordDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user/borrowBook")
public class BorrowBookServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int bookId = Integer.parseInt(request.getParameter("bookId"));
        HttpSession session = request.getSession();
        int userId = ((com.library.entity.User) session.getAttribute("user")).getId();

        BorrowRecordDAO recordDAO = new BorrowRecordDAO();
        boolean success = recordDAO.borrowBook(userId, bookId);

        if (success) {
            request.setAttribute("message", "借阅成功");
        } else {
            request.setAttribute("error", "借阅失败，可能是图书已被借出");
        }
        request.getRequestDispatcher("/user/books").forward(request, response);
    }
}    